﻿using System;
using System.Windows.Forms;
using Meridian;
using MessageBox = System.Windows.MessageBox;

namespace MeridianZ.Helpers
{
    public class AuthHelper
    {
        public static void Authorize(Action callback)
        {
            string authUrl = App.Vkontakte.GetAuthUrl(new[] { "audio" });
            var form = new Form();
            form.Width = 640;
            form.Height = 480;
            form.StartPosition = FormStartPosition.CenterScreen;
            form.Text = Properties.Resources.AuthWindowTitle;

            var browser = new WebBrowser();
            browser.Dock = DockStyle.Fill;
            browser.Navigated += (s, e) =>
                                     {
                                         VkApi.VkAuthResult authResult;
                                         if (VkApi.VkAuthResult.TryParse(e.Url, out authResult))
                                         {
                                             form.ShowInTaskbar = true;
                                             if (!authResult.IsSuccess)
                                             {
                                                 MessageBox.Show("Authorization failed!");
                                                 return;
                                             }

                                             App.Vkontakte.AuthResult = authResult;
                                             Global.IsAuthorized = true;
                                             form.Close();
                                             callback();
                                         }
                                         else
                                         {
                                             form.FormBorderStyle = FormBorderStyle.Sizable;
                                             form.Opacity = 1;
                                         }
                                     };


            browser.Navigate(authUrl);
            form.Controls.Add(browser);
            form.FormBorderStyle = FormBorderStyle.None;
            form.Opacity = 0;
            form.ShowInTaskbar = false;
            form.ShowDialog();
        }
    }
}
